<template>
  <div class="schedule-preview">
    <div class="page-header">
      <h1>排班预览</h1>
      <p>按星期和医生查看排班情况</p>
    </div>
    
    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" inline>
        <el-form-item label="科室">
          <el-tree-select 
            v-model="filterForm.departmentId" 
            placeholder="请选择科室"
            clearable
            filterable
            @change="handleFilterChange"
            :data="departmentTree"
            node-key="id"
            :props="{
              label: 'name',
              value: 'id',
              children: 'children'
            }"
            check-strictly
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="周次">
          <el-date-picker
            v-model="filterForm.weekDate"
            type="week"
            format="YYYY 第 WW 周"
            value-format="YYYY-MM-DD"
            placeholder="选择周次"
            @change="handleFilterChange"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilterChange">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 排班预览表格 -->
    <el-card class="preview-card" shadow="never">
      <template #header>
        <div class="card-header">
          <span>排班预览表</span>
        </div>
      </template>

      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>

      <!-- 排班表格 -->
      <div v-else-if="scheduleData.length > 0" class="schedule-table-container">
        <el-table 
          :data="scheduleData" 
          border 
          stripe
          style="width: 100%"
          :header-cell-style="{ background: '#f5f7fa' }"
          size="small"
        >
          <!-- 医生信息列 -->
          <el-table-column label="医生信息" width="150" fixed="left">
            <template #default="{ row }">
              <div class="doctor-info">
                <div class="doctor-name">{{ row.doctorName }}</div>
                <div class="doctor-department">{{ row.departmentName }}</div>
              </div>
            </template>
          </el-table-column>
          
          <!-- 星期列 -->
          <el-table-column 
            v-for="day in weekDays" 
            :key="day.date"
            :label="day.label" 
            :width="120"
            align="center"
          >
            <template #default="{ row }">
              <div class="day-schedules">
                <div 
                  v-for="schedule in getSchedulesByDate(row.schedules, day.date)"
                  :key="schedule.id"
                  class="schedule-item"
                  :class="getScheduleItemClass(schedule)"
                >
                  <div class="time-slot">
                    <el-tag :type="getTimeSlotTagType(schedule.timeSlot)" size="small">
                      {{ getTimeSlotName(schedule.timeSlot) }}
                    </el-tag>
                  </div>
                  <div class="time-range">{{ schedule.startTime }}-{{ schedule.endTime }}</div>
                  <div class="status-info">
                    <el-tag :type="getStatusTagType(schedule.status)" size="small">
                      {{ getStatusName(schedule.status) }}
                    </el-tag>
                  </div>
                  <div class="booking-info">
                    {{ schedule.bookedCount }}/{{ schedule.availableCount }}
                  </div>
                </div>
                <div v-if="getSchedulesByDate(row.schedules, day.date).length === 0" class="no-schedule">
                  <el-text type="info" size="small">无排班</el-text>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 空状态 -->
      <div v-else class="empty-container">
        <el-empty description="暂无排班数据" />
      </div>
    </el-card>

    <!-- 统计信息 -->
    <el-card class="statistics-card" shadow="never">
      <template #header>
        <span>统计信息</span>
      </template>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ statistics.totalSchedules || 0 }}</div>
            <div class="stat-label">总排班数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ statistics.normalSchedules || 0 }}</div>
            <div class="stat-label">正常排班</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ statistics.cancelledSchedules || 0 }}</div>
            <div class="stat-label">停诊排班</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-number">{{ statistics.fullSchedules || 0 }}</div>
            <div class="stat-label">满号排班</div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Search
} from '@element-plus/icons-vue'
import { 
  getScheduleList,
  getScheduleStatistics
} from '@/api/business'
import { getDepartmentTree } from '@/api/business'

// 响应式数据
const loading = ref(false)
const departmentTree = ref([])
const scheduleData = ref([])
const statistics = ref({})

// 筛选表单
const filterForm = reactive({
  departmentId: null,
  weekDate: null
})

// 计算属性 - 生成一周的日期
const weekDays = computed(() => {
  if (!filterForm.weekDate) {
    return []
  }
  
  const weekStart = new Date(filterForm.weekDate)
  const weekDays = []
  const dayNames = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
  
  for (let i = 0; i < 7; i++) {
    const date = new Date(weekStart)
    date.setDate(weekStart.getDate() + i)
    weekDays.push({
      date: date.toISOString().split('T')[0],
      label: `${dayNames[i]}\n${date.getMonth() + 1}/${date.getDate()}`,
      dayName: dayNames[i]
    })
  }
  
  return weekDays
})

// 工具方法
const getTimeSlotName = (timeSlot) => {
  const map = { 1: '上午', 2: '下午', 3: '晚上' }
  return map[timeSlot] || '未知'
}

const getTimeSlotTagType = (timeSlot) => {
  const map = { 1: 'success', 2: 'warning', 3: 'info' }
  return map[timeSlot] || ''
}

const getStatusName = (status) => {
  const map = { 0: '停诊', 1: '正常', 2: '满号' }
  return map[status] || '未知'
}

const getStatusTagType = (status) => {
  const map = { 0: 'danger', 1: 'success', 2: 'warning' }
  return map[status] || ''
}

const getSchedulesByDate = (schedules, date) => {
  if (!schedules) return []
  return schedules.filter(schedule => schedule.scheduleDate === date)
}

const getScheduleItemClass = (schedule) => {
  return {
    'schedule-normal': schedule.status === 1,
    'schedule-cancelled': schedule.status === 0,
    'schedule-full': schedule.status === 2
  }
}

// 获取科室树形数据
const fetchDepartmentTree = async () => {
  try {
    const response = await getDepartmentTree()
    if (response.code === 200) {
      departmentTree.value = response.data || []
    }
  } catch (error) {
    console.error('获取科室树形数据失败:', error)
  }
}

// 获取排班数据
const fetchScheduleData = async () => {
  if (!filterForm.weekDate) {
    scheduleData.value = []
    return
  }
  
  loading.value = true
  try {
    // 计算一周的开始和结束日期
    const weekStart = new Date(filterForm.weekDate)
    const weekEnd = new Date(weekStart)
    weekEnd.setDate(weekStart.getDate() + 6)
    
    const params = {
      departmentId: filterForm.departmentId,
      startDate: weekStart.toISOString().split('T')[0],
      endDate: weekEnd.toISOString().split('T')[0],
      page: 1,
      size: 500
    }

    console.log('请求参数:', params)

    const response = await getScheduleList(params)
    console.log('API响应:', response)
    
    if (response.code === 200) {
      let schedules = []
      if (response.data && response.data.list) {
        schedules = response.data.list || []
      } else {
        schedules = response.data || []
      }
      
      console.log('解析后的排班数据:', schedules)
      
      // 按医生分组排班数据
      const groupedData = groupSchedulesByDoctor(schedules)
      console.log('分组后的数据:', groupedData)
      scheduleData.value = groupedData
    }
  } catch (error) {
    console.error('获取排班数据失败:', error)
    ElMessage.error('获取排班数据失败')
  } finally {
    loading.value = false
  }
}

// 按医生分组排班数据
const groupSchedulesByDoctor = (schedules) => {
  console.log('开始按医生分组，原始数据:', schedules)
  
  const grouped = {}
  
  schedules.forEach(schedule => {
    const doctorKey = `${schedule.doctorId}-${schedule.doctorName}`
    if (!grouped[doctorKey]) {
      grouped[doctorKey] = {
        doctorId: schedule.doctorId,
        doctorName: schedule.doctorName,
        departmentName: schedule.departmentName,
        schedules: []
      }
    }
    grouped[doctorKey].schedules.push(schedule)
  })
  
  const result = Object.values(grouped).sort((a, b) => {
    // 按医生姓名排序
    return a.doctorName.localeCompare(b.doctorName)
  })
  
  console.log('分组完成，结果:', result)
  return result
}

// 获取统计数据
const fetchStatistics = async () => {
  if (!filterForm.weekDate) {
    statistics.value = {}
    return
  }
  
  try {
    const weekStart = new Date(filterForm.weekDate)
    const weekEnd = new Date(weekStart)
    weekEnd.setDate(weekStart.getDate() + 6)
    
    const params = {
      startDate: weekStart.toISOString().split('T')[0],
      endDate: weekEnd.toISOString().split('T')[0],
      departmentId: filterForm.departmentId
    }
    
    const response = await getScheduleStatistics(params)
    if (response.code === 200) {
      statistics.value = response.data || {}
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 事件处理
const handleFilterChange = () => {
  fetchScheduleData()
  fetchStatistics()
}

const resetFilter = () => {
  Object.assign(filterForm, {
    departmentId: null,
    weekDate: null
  })
  handleFilterChange()
}

// 生命周期
onMounted(() => {
  fetchDepartmentTree()
  // 默认显示当前周
  const today = new Date()
  const dayOfWeek = today.getDay()
  const monday = new Date(today)
  monday.setDate(today.getDate() - dayOfWeek + (dayOfWeek === 0 ? -6 : 1))
  filterForm.weekDate = monday.toISOString().split('T')[0]
  handleFilterChange()
})
</script>

<style scoped>
.schedule-preview {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.filter-card {
  margin-bottom: 20px;
}

.preview-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 40px;
}

.empty-container {
  padding: 60px;
  text-align: center;
}

.schedule-table-container {
  overflow-x: auto;
}

.doctor-info {
  text-align: left;
  padding: 8px;
}

.doctor-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  margin-bottom: 4px;
}

.doctor-department {
  color: #606266;
  font-size: 12px;
}

.day-schedules {
  min-height: 80px;
  padding: 4px;
}

.schedule-item {
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 6px;
  margin-bottom: 6px;
  font-size: 11px;
}

.schedule-item:last-child {
  margin-bottom: 0;
}

.schedule-normal {
  background: #f0f9ff;
  border-color: #91d5ff;
}

.schedule-cancelled {
  background: #fef0f0;
  border-color: #ffa39e;
}

.schedule-full {
  background: #fff7e6;
  border-color: #ffd591;
}

.time-slot {
  margin-bottom: 4px;
}

.time-range {
  color: #606266;
  margin-bottom: 4px;
  font-size: 10px;
}

.status-info {
  margin-bottom: 4px;
}

.booking-info {
  color: #909399;
  font-size: 10px;
}

.no-schedule {
  text-align: center;
  padding: 20px 0;
}

.statistics-card {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 20px;
}

.stat-number {
  font-size: 28px;
  font-weight: 600;
  color: #409eff;
  margin-bottom: 8px;
}

.stat-label {
  color: #606266;
  font-size: 14px;
}
</style> 